//
//  YHHomeRateRevisionViewController.m
//  YHApp
//
//  Created by -- on 2021/7/14.
//

#import "HARateRevisionVC.h"
#import "HAMachineRateMakeMo.h"
#import "HARateRevisionCell.h"
#import "HASMSendVC.h"
#import "HAChooseTabPopView.h"

@interface HARateRevisionVC () <UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic ,strong) NSMutableArray *dataArray;
/***/
@property (nonatomic, strong) UITextField *seachField;
/***/
@property (nonatomic, strong) HAMachineRateMakeMo *model;


@end

@implementation HARateRevisionVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.baseTLabel.text = @"费率查询";

    [self setupUI];
    
//    self.seachField.text = @"N5810000032";
    
    // Do any additional setup after loading the view.
}

-(void)scanSodeBtnClick {
    [self.view endEditing:YES];
    WS(weakSelf)
    if ([HAHelper isCamera]) {
        HASMSendVC *vc = [[HASMSendVC alloc]init];
        [vc retrunBlock:^(NSString * _Nonnull snText) {
            weakSelf.seachField.text = snText;
//            [weakSelf loadData:snText];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        HATipsPopView *menu = [[HATipsPopView alloc]initWithTitle:@"温馨提示" content:@"请允许访问您的相机" left:@"取消" right:@"去设置"];
        [menu show];
        menu.XZYGTiShiRightBlock = ^{
            [HAHelper GetPhoneSet];
        };
    }
}

-(void)seachBtnClick {
    [self.view endEditing:YES];
    
    if ([NSString isEmptyString:self.seachField.text]) {
        [MBProgressHUD showError:@"请输入机具SN/商户名称"];
        return;
    }
    [self loadDataWith:self.seachField.text];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];

    if ([NSString isEmptyString:self.seachField.text]) {
        [MBProgressHUD showError:@"请输入机具SN/商户名称"];
        return NO;
    }

    [self loadDataWith:self.seachField.text];
    
    return YES;
}


-(void)setupUI {
    
    UIView *bgV = [UIView ha_createView];
    bgV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgV];
    [bgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(app_topH+44+1);
        make.height.mas_offset(98);
    }];
    
    UIButton *scanSodeBtn = [[UIButton alloc]init];
    [scanSodeBtn setImage:[UIImage imageNamed:@"ha_11"] forState:UIControlStateNormal];
    [scanSodeBtn addTarget:self action:@selector(scanSodeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [bgV addSubview:scanSodeBtn];
    [scanSodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(20);
        make.width.mas_offset(22);
        make.height.mas_offset(22);
    }];
    
    UIButton *seachBtn = [[UIButton alloc]init];
    [seachBtn setImage:[UIImage imageNamed:@"ha_searchIcon"] forState:UIControlStateNormal];
    [seachBtn addTarget:self action:@selector(seachBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [bgV addSubview:seachBtn];
    [seachBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.top.mas_equalTo(20);
        make.width.mas_offset(22);
        make.height.mas_offset(22);
    }];
    
    UITextField *seachField = [[UITextField alloc]init];
    self.seachField = seachField;
    seachField.delegate = self;
    seachField.placeholder = @"请输入机具SN/商户名称";
    seachField.font = [UIFont systemFontOfSize:18];
    seachField.returnKeyType = UIReturnKeySearch;
    [bgV addSubview:seachField];
    [seachField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(scanSodeBtn.mas_right).offset(10);
        make.right.equalTo(seachBtn.mas_left).offset(-10);
        make.centerY.mas_equalTo(seachBtn);
        make.height.equalTo(@28);
    }];

    UILabel *tipsLabel = [[UILabel alloc]init];
    tipsLabel.text = @"机具绑定商户有一笔交易后才可以修改费率。只允许修改本级直属商户的费率，越级不允许操作。";
    tipsLabel.font = [UIFont systemFontOfSize:10];
    tipsLabel.textColor = [UIColor colorWithHexString:@"#666666"];
    tipsLabel.numberOfLines = 0;
    [bgV addSubview:tipsLabel];
    [tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-5);
        make.left.mas_equalTo(12);
        make.right.mas_equalTo(-12);
    }];

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(bgV.mas_bottom);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];

}

-(void)loadDataWith:(NSString *)key {
    WS(weakSelf)
    SYRequest *request = [[SYRequest alloc]init];
    request.requestMethod = SYRequestMethodPOST;
    request.requestUrl = @"customer/cuss";
    request.parms = @{
        @"keyword":key,
    };

    [MBProgressHUD showLoading:self.view];
    
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request) {
            [MBProgressHUD hideHUDForView:self.view];
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                if ([dataModel.data isKindOfClass:[NSArray class]]) {
                    NSArray *arr = dataModel.data;
                    if (arr.count > 0) {
                        NSMutableArray *dicts = [NSMutableArray array];
                        for (int i = 0; i < arr.count; i++) {
                            NSDictionary *dict = arr[i];
                            NSString *name = @"";
                            if ([[dict allKeys] containsObject:@"surname"]) {
                                name = [NSString stringWithFormat:@"%@", dict[@"surname"]];
                            }
                            NSString *term_sn = @"";
                            if ([[dict allKeys] containsObject:@"term_sn"]) {
                                term_sn = [NSString stringWithFormat:@"%@", dict[@"term_sn"]];
                            }
                            [dicts addObject:@{@"color":@"#373737",@"title":name,@"term_sn":term_sn,}];
                        }
                        
                        if (dicts.count == 1) {
                            [weakSelf loadSnData:dicts.firstObject[@"term_sn"]];
                        }
                        if (dicts.count > 1) {
                            HAChooseTabPopView *menu = [[HAChooseTabPopView alloc]initWithDicts:dicts title:@"请选择商户"];
                            menu.YHChooseTabMenuCellSureBlock = ^(NSDictionary * _Nonnull dic) {
                                [weakSelf loadSnData:dic[@"term_sn"]];
                            };
                            [menu show];
                        }
                    }
                }
                
            }else {
                [MBProgressHUD showError:dataModel.msg];
            }
        }
    }];

}


-(void)loadSnData:(NSString *)sn {
    SYRequest *request = [[SYRequest alloc]init];
    request.requestMethod = SYRequestMethodGET;
    request.requestUrl = @"customer/rate.html";
    request.parms = @{
        @"sn":sn,
    };
    [MBProgressHUD showLoading:self.view];
    [self.dataArray removeAllObjects];

    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request) {
            [MBProgressHUD hideHUDForView:self.view];
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                self.model = [HAMachineRateMakeMo mj_objectWithKeyValues:dataModel.data];
                if (self.model.rates.count > 0) {
                    [self.dataArray addObject:@"内容"];
                    [self.dataArray addObject:@"提交"];
//                    if (self.model.disabled == YES) {
//                        [self.dataArray addObject:@"提交"];
//                    }
                }
            }else {
                [MBProgressHUD showError:dataModel.msg];
            }
            [self.tableView reloadData];
        }
    }];

}

-(void)mitButtonClick {
    [self.view endEditing:YES];

    NSMutableArray *mitAateArr = [NSMutableArray array];
    for (int i = 0; i < self.model.rates.count; i ++) {
        YHMachineRateMakeRatesModel *rateMo = self.model.rates[i];
        for (int j = 0; j < rateMo.item.count; j ++) {
            YHMachineRateMakeItemModel *item = rateMo.item[j];
            [mitAateArr addObject:@{
                @"value":item.value?:@"",
                @"field":item.field?:@"",
            }];
        }
    }
    
    SYRequest *request = [[SYRequest alloc]init];
    request.requestMethod = SYRequestMethodPOST;
    request.requestUrl = [NSString stringWithFormat:@"rate/trade.html?sn=%@",self.model.sn];
    request.parms = @{
        @"items":[mitAateArr mj_JSONString],
    };
    [MBProgressHUD showLoading:self.view];
    
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request) {
            [MBProgressHUD hideHUDForView:self.view];
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                [MBProgressHUD showSuccess:@"提交成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }else {
                [MBProgressHUD showError:dataModel.msg];
            }
        }
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *title = self.dataArray[indexPath.row];
    if ([title isEqualToString:@"内容"]) {
        CGFloat h = 0;
        h += 54*3;
        for (int i = 0; i < self.model.rates.count; i ++) {
            YHMachineRateMakeRatesModel *rateMo = self.model.rates[i];
            h += 54;
            h += (54+28) * rateMo.item.count;
        }
        return h;
    }
    if ([title isEqualToString:@"提交"]) {
        return 54+60;
    }
    return 0;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *title = self.dataArray[indexPath.row];
    if ([title isEqualToString:@"内容"]) {
        HARateRevisionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HARateRevisionCellID"];
        if (!cell) {
            cell = [[HARateRevisionCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HARateRevisionCellID"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.model;
        return cell;
    }
    if ([title isEqualToString:@"提交"]) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HAMachineRateMakeMitCellID"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HAMachineRateMakeMitCellID"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setCellMit:cell.contentView];
        return cell;
    }
    return [UITableViewCell new];
}

-(void)setCellMit:(UIView *)contentView {
    for (UIView *view in contentView.subviews) {
        [view removeFromSuperview];
    }
    contentView.backgroundColor = [UIColor khaBGColor];
    UIButton *mitButton = [[UIButton alloc]init];
    [mitButton setTitle:@"提交" forState:UIControlStateNormal];
    [mitButton setTitleColor:[UIColor colorWithHexString:@"#FFFFFF"] forState:UIControlStateNormal];
    mitButton.titleLabel.font = [UIFont systemFontOfSize:20];
    mitButton.backgroundColor = [UIColor colorWithHexString:@"#19191A"];
    [mitButton addTarget:self action:@selector(mitButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:mitButton];
    [mitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(25);
        make.right.mas_equalTo(-25);
        make.centerY.mas_equalTo(0);
        make.height.mas_offset(54);
    }];
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
        // 去掉滚动条
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;

        // 设置背景颜色
        _tableView.backgroundColor = [UIColor khaBGColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark - 无数据处理 DZNEmptyDataSetSource DZNEmptyDataSetDelegate
//设置title
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"暂无数据~";
    NSDictionary *attributes = @{
        NSFontAttributeName:[UIFont systemFontOfSize:14],
        NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#999999"]
    };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}


//设置image
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"hl_nodata"];
}

@end
